﻿using HtmlAgilityPack;
using Spider.Analyse;
using Spider.Entitys.天气预报各级实体对象;
using Spider.Rules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spider.HTMLAnalyse.天气预报各级HTML解析
{
    public class 天气预报每天解析 : AnalyseBase, IAnalyse
    {
        public override List<T> GetListData<T>(HtmlDocument doc, IRule rule, object o = null)
        {
            List<T> listEntity = new List<T>();
            //更加xpath获取总的对象，如果不为空，就继续选择dl标签
            HtmlNode res = doc.DocumentNode.SelectSingleNode(rule.RuleXPathString());
            if (res != null)
            {
                var trlist = res.SelectNodes(@"tr");//选择标签数组
                bool flag = false;
                foreach (var tr in trlist)
                {
                    var tdlist = tr.SelectNodes(@"td");
                    var td1 = tdlist[0];
                    //flag 的作用是如果已经发现了表头，不用再用正则表达式去匹配了，节省系统资源
                    if (!flag)
                    {
                        if (td1.InnerText.AnalyseRegexResult(".*(日期).*") == "日期")
                        {
                            //如果发现是表格的表头，跳过
                            flag = true;
                            continue;
                        }
                    }
                    var td2 = tdlist[1];
                    var td3 = tdlist[2];
                    var td4 = tdlist[3];
                    天气预报天 entity = new 天气预报天()
                    {
                        URL = td1.InnerHtml.GetHref(),
                        日期 = td1.InnerText.Replace(" ", "").Replace("\r\n", ""),
                        天气状况 = td2.InnerText.Replace(" ", "").Replace("\r\n", ""),
                        气温 = td3.InnerText.Replace(" ", "").Replace("\r\n", ""),
                        风力风向 = td4.InnerText.Replace(" ", "").Replace("\r\n", "")
                    };
                    listEntity.Add((T)(object)entity);
                }
            }
            return listEntity;
        }
    }
}
